<template>
  <div class="dashboard-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <h1 class="logo">校园智慧竞赛平台 - 管理后台</h1>
      </div>
      <div class="header-right">
        <span class="admin-name">{{ adminName }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <nav class="nav-menu">
          <div class="menu-item" @click="navigateTo('/dashboard')">
            <i class="icon">📊</i>
            <span>仪表盘</span>
          </div>
          <div class="menu-item" @click="navigateTo('/user-audit')">
            <i class="icon">👥</i>
            <span>用户审核</span>
          </div>
          <div class="menu-item" @click="navigateTo('/user-management')">
            <i class="icon">👤</i>
            <span>用户管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/team-management')">
            <i class="icon">⚡</i>
            <span>队伍管理</span>
          </div>
          <div class="menu-item active">
            <i class="icon">🏠</i>
            <span>主页编辑</span>
          </div>
          <div class="menu-item" @click="navigateTo('/system-notifications')">
            <i class="icon">📢</i>
            <span>通知管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/news-management')">
            <i class="icon">📰</i>
            <span>新闻管理</span>
          </div>
        <div class="menu-item" @click="navigateTo('/event-management')">
          <i class="icon">🏆</i>
          <span>赛事管理</span>
        </div>
        </nav>
      </aside>

      <!-- 主要内容区域 -->
      <main class="content">
        <div class="page-header">
          <h2>主页编辑</h2>
          <div class="header-actions">
            <button class="save-btn" @click="saveChanges" :disabled="saving">
              {{ saving ? '刷新中...' : '刷新数据' }}
            </button>
          </div>
        </div>

        <!-- 编辑区域 -->
        <div class="editor-container">
          <!-- 轮播图编辑 -->
          <div class="editor-section">
            <h3>轮播图管理</h3>
            <p class="section-desc">管理首页轮播图，共6个位置，点击方块上传对应位置的图片</p>

            <div class="carousel-grid">
              <div
                v-for="(carousel, index) in carouselImages"
                :key="carousel.position"
                class="carousel-item"
              >
                <div class="carousel-position">位置 {{ carousel.position }}</div>

                <!-- 上传中状态 -->
                <div v-if="carousel.uploading" class="uploading-state">
                  <div class="upload-icon">⏳</div>
                  <p>上传中...</p>
                </div>

                <!-- 已上传图片显示 -->
                <div v-else-if="carousel.imageUrl" class="carousel-image">
                  <img :src="carousel.imageUrl" :alt="carousel.imageName" />
                  <div class="image-overlay">
                    <button class="change-btn" @click="changeImage(index)">更换</button>
                    <!-- <button class="remove-btn" @click="removeImage(index)">删除</button> -->
                  </div>
                </div>

                <!-- 未上传状态 -->
                <div v-else class="upload-placeholder" @click="uploadImage(index)">
                  <div class="upload-icon">📷</div>
                  <p>点击上传图片</p>
                  <p class="upload-tip">支持 JPG、PNG、GIF、WebP，最大 10MB，建议尺寸 1200x400</p>
              
                </div>

                <!-- 隐藏的文件输入框 -->
                <input
                  :data-index="index"
                  type="file"
                  @change="handleImageUpload($event, index)"
                  accept="image/*"
                  style="display: none"
                />
              </div>
            </div>
          </div>


        </div>
      </main>
    </div>



    <!-- 消息提示 -->
    <div v-if="showMessage" class="message-toast" :class="messageType">
      {{ messageText }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import { getCarouselImagesService, updateCarouselImageService, uploadCarouselImageService } from '@/api/admin.js'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 数据状态
const saving = ref(false)

// 轮播图数据
const carouselImages = ref([])

// 消息提示
const showMessage = ref(false)
const messageText = ref('')
const messageType = ref('success')

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 显示消息
const showMessageToast = (text, type = 'success') => {
  messageText.value = text
  messageType.value = type
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 3000)
}

// 上传图片
const uploadImage = (index) => {
  const fileInput = document.querySelector(`input[data-index="${index}"]`)
  if (fileInput) {
    fileInput.click()
  }
}

// 更换图片
const changeImage = (index) => {
  uploadImage(index)
}

// 处理图片上传
const handleImageUpload = async (event, index) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    showMessageToast('请选择支持的图片格式（JPG、PNG、GIF、WebP）', 'error')
    return
  }

  // 验证文件大小（10MB）
  if (file.size > 10 * 1024 * 1024) {
    showMessageToast('图片大小不能超过10MB', 'error')
    return
  }

  try {
    // 显示上传中状态
    carouselImages.value[index].uploading = true

    // 上传图片到服务器
    const uploadResult = await uploadCarouselImageService(file)
    if (uploadResult.code === 200) {
      // 上传成功，更新轮播图数据
      const updateResult = await updateCarouselImageService(carouselImages.value[index].position, {
        imageUrl: uploadResult.data.url,
        imageName: file.name,
        isActive: true
      })

      if (updateResult.code === 200) {
        // 更新本地数据
        carouselImages.value[index].imageUrl = uploadResult.data.url
        carouselImages.value[index].imageName = file.name
        carouselImages.value[index].isActive = true
        showMessageToast('图片上传成功')
      } else {
        showMessageToast(updateResult.message || '更新轮播图失败', 'error')
      }
    } else {
      showMessageToast(uploadResult.message || '图片上传失败', 'error')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    showMessageToast('图片上传失败，请稍后重试', 'error')
  } finally {
    carouselImages.value[index].uploading = false
    // 清空文件输入框
    event.target.value = ''
  }
}

// 删除图片
const removeImage = async (index) => {
  try {
    const position = carouselImages.value[index].position
    const result = await updateCarouselImageService(position, {
      imageUrl: '',
      imageName: `轮播图${position}`,
      isActive: true
    })

    if (result.code === 200) {
      // 更新本地数据
      carouselImages.value[index].imageUrl = ''
      carouselImages.value[index].imageName = `轮播图${position}`
      showMessageToast('图片删除成功')
    } else {
      showMessageToast(result.message || '删除失败', 'error')
    }
  } catch (error) {
    console.error('删除图片失败:', error)
    showMessageToast('删除失败，请稍后重试', 'error')
  }
}



// 保存更改（现在主要用于刷新数据）
const saveChanges = async () => {
  saving.value = true
  try {
    await loadCarouselImages()
    showMessageToast('数据刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    showMessageToast('刷新失败，请稍后重试', 'error')
  } finally {
    saving.value = false
  }
}

// 加载轮播图数据
const loadCarouselImages = async () => {
  try {
    const result = await getCarouselImagesService()
    if (result.code === 200 && result.data) {
      // 确保有6条记录，按position排序
      const sortedData = result.data.sort((a, b) => a.position - b.position)

      // 初始化6个位置的数据
      carouselImages.value = []
      for (let i = 1; i <= 6; i++) {
        const existingItem = sortedData.find(item => item.position === i)
        carouselImages.value.push({
          id: existingItem?.id || null,
          position: i,
          imageUrl: existingItem?.imageUrl || '',
          imageName: existingItem?.imageName || `轮播图${i}`,
          isActive: existingItem?.isActive !== undefined ? existingItem.isActive : true,
          uploading: false
        })
      }
    }
  } catch (error) {
    console.error('加载轮播图数据失败:', error)
    showMessageToast('加载轮播图数据失败', 'error')
  }
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadCarouselImages()
})
</script>

<style scoped>
@import '@/assets/css/HomepageEditor.css';
</style>
